<!--
 * @Author: guandeshen 295570679@qq.com
 * @Date: 2024-08-25 09:54:45
 * @LastEditors: guandeshen 295570679@qq.com
 * @LastEditTime: 2024-09-10 11:28:00
 * @FilePath: /task-admin/src/views/task/components/AddPersonnel/index.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by RSC, All Rights Reserved. 
-->
<template>
  <div class="content">
    <!-- 添加人员 -->
    <div class="table-box">
      <el-table
        :data="newUserData"
        :stripe="true"
        :header-cell-style="{
          'background-color': '#F6F7F9',
          color: '#8B8B99',
        }"
        style="width: 100%"
      >
        <el-table-column
          :label="$t('common.nickName')"
          :show-overflow-tooltip="true"
          :min-width="140"
        >
          <template #default="scope">
            <span v-if="scope.row.ref">{{ scope.row.nickname }}</span>
            <el-select
              :placeholder="$t('common.pleaseSelect')"
              v-else
              v-model="scope.row.user_ref"
              @change="handleChange($event, scope.row)"
            >
              <el-option
                v-for="option of userOption"
                :key="option.id"
                :label="option.nickname"
                :value="option.id"
              />
            </el-select>
            <!--  -->
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('common.Gender')"
          :show-overflow-tooltip="true"
          :min-width="100"
        >
          <template #default="scope">
            <span v-if="scope.row.ref">{{
              scope.row.gender == 1 ? $t("common.female") : $t("common.male")
            }}</span>
            <el-input
              v-else
              :value="
                scope.row.gender == 1
                  ? $t('common.female')
                  : scope.row.gender == -1
                    ? ''
                    : $t('common.male')
              "
              :placeholder="$t('common.autofill')"
              disabled
            />
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.cellPhoneNumber')"
          :show-overflow-tooltip="true"
          :min-width="140"
        >
          <template #default="scope">
            <span v-if="scope.row.ref">{{ scope.row.mobile }}</span>
            <el-input
              v-else
              v-model="scope.row.mobile"
              :placeholder="$t('common.autofill')"
              disabled
            />
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.perDiem')"
          :show-overflow-tooltip="true"
          :min-width="100"
        >
          <template #default="scope">
            <span v-if="scope.row.ref">{{ scope.row.daily_wage }}</span>
            <el-input
              v-else
              v-model="scope.row.daily_wage"
              :placeholder="$t('common.autofill')"
              disabled
            />
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.jobTypes')"
          :show-overflow-tooltip="true"
          :min-width="140"
        >
          <template #default="scope">
            <span v-if="scope.row.ref">{{ scope.row.type_of_work }}</span>
            <el-input
              v-else
              v-model="scope.row.type_of_work"
              :placeholder="$t('common.autofill')"
              disabled
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.days')" :min-width="120">
          <template #default="scope">
            <span v-if="scope.row.ref">{{ scope.row.days }}</span>
            <el-input-number
              v-else
              style="width: 120px"
              v-model="scope.row.days"
              :min="1"
            />
          </template>
        </el-table-column>
        <el-table-column
          v-if="viewType != 1"
          :label="$t('common.operation')"
          :min-width="80"
        >
          <template #default="{ $index, row }">
            <el-button
              :disabled="row.id == '-1' ? false : true"
              type="danger"
              icon="delete"
              link
              @click="handleDeleteClick($index, row.id)"
            >
              {{ $t("common.delete") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <span
      v-if="viewType != 1"
      class="flex-center h-42px border-rd-8px bg-#F2F3F5 text-[#323233] font-900 text-14px cursor-pointer mt-16px hover:bg-#4E6BEF hover:text-[#fff]"
      @click="handleAddClick"
      ><i-ep-plus class="close-icon mr-10px font-900" size="12px" />{{
        $t("common.add")
      }}</span
    >
  </div>
</template>

<script lang="ts" setup>
import { watchEffect } from "vue";
import { TaskUsers } from "@/api/task/model";
import UserAPI from "@/api/user";
import { TenantList } from "@/api/user/model";
import ProjectAPI from "@/api/project";
const { t } = useI18n();
const props = withDefaults(
  defineProps<{
    userData: TaskUsers[] | undefined;
    viewType: number;
    wbsId: string;
  }>(),
  {
    userData: () => {
      return [];
    },
    viewType: 2,
  }
);
const newUserData = ref<TaskUsers[]>([]);
watchEffect(() => {
  newUserData.value = props.userData;
  // 这里可以执行更多响应式的副作用代码
});

// 点击删除
const handleDeleteClick = (index: number, id: string) => {
  if (id == "-1") {
    newUserData.value.splice(index, 1);
  } else {
    ElMessageBox.confirm(t("common.confirmDeletion"), t("common.warning"), {
      confirmButtonText: t("common.confirm"),
      cancelButtonText: t("common.cancel"),
      type: "warning",
    }).then(function () {
      ProjectAPI.deleteUserByIds({
        wbs_id: props.wbsId,
        wbs_user_id: id,
      }).then(() => {
        ElMessage.success(t("common.deleteSuccessful"));
        newUserData.value.splice(index, 1);
      });
    });
  }
};

// const siteRef = ref<InstanceType<typeof PageContent>>();
const addRow = ref<TaskUsers>({
  id: "-1",
  ref: "",
  user_ref: "",
  nickname: "",
  mobile: "",
  daily_wage: "0",
  type_of_work: "",
  days: 1,
  gender: -1,
});

// export interface TaskUsers {
//   id?: string;
//   ref?: string;
//   daily_wage?: string;
//   user_ref?: string;
//   nickname?: string;
//   type_of_work?: string;
//   created?: string;
// }

const handleAddClick = () => {
  // 点添加的时候判断当前有没有新增的行，如果有判断是否全部已经填写，没有就提示，有就把ref给个随机值，然后增加一条数据
  if (newUserData.value.some((item) => item.user_ref === "")) {
    ElMessage.error(t("common.pleaseFillFirst"));
    return;
  }
  if (newUserData.value.length > 0) {
    newUserData.value[newUserData.value.length - 1].ref =
      Math.random().toString(36);
  }

  newUserData.value.push(JSON.parse(JSON.stringify(addRow.value)));
};

const userOption = ref<TenantList[]>([]);
const getUserOption = () => {
  UserAPI.getTenantList({
    page: 1,
    page_size: 100000000,
  }).then((data) => {
    userOption.value = data.list;
  });
};
const initData = () => {
  getUserOption();
};

// 选择商品
const handleChange = (value: any, row: TaskUsers) => {
  const index = userOption.value.findIndex((option) => option.id === value);
  row.nickname = userOption.value[index].nickname;
  row.type_of_work = userOption.value[index].type_of_work;
  row.gender = userOption.value[index].gender;
  row.mobile = userOption.value[index].mobile;
  row.daily_wage = userOption.value[index].daily_wage;
};
onMounted(() => {
  initData();
});
defineExpose({ newUserData });
</script>

<style scoped>
/* @import url(); 引入公共css类 */
:deep(.table-box) {
  margin-top: 0 !important;
  padding: 0 !important;
}
</style>
